package com.ycz.zheng_springboot.service.impl;



import cn.hutool.core.collection.CollUtil;
import com.ycz.zheng_springboot.entity.Menu;
import com.ycz.zheng_springboot.entity.RoleMenu;
import com.ycz.zheng_springboot.mapper.RoleMenuMapper;
import com.ycz.zheng_springboot.service.IMenuService;
import com.ycz.zheng_springboot.service.IRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色菜单关系表 服务实现类
 * </p>
 *
 * @author 岳彩郑
 * @since 2022-05-06
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private IMenuService menuService;

    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
//        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("role_id", roleId);
//        roleMenuMapper.delete(queryWrapper);

        // 删除原有的角色菜单关系
        roleMenuMapper.deleteByRoleId(roleId);

        // 添加新的角色菜单关系  从前端传过来的menuIds数组绑定在当前角色id下
        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            Menu menu = menuService.getById(menuId);
            if (menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())) { // 二级菜单 并且传过来的menuId数组里面没有它的父级id
                // 那么我们就得补上这个父级id
                roleMenu.setRoleId(roleId);// 角色id
                roleMenu.setMenuId(menu.getPid());// 菜单id
                roleMenuMapper.insert(roleMenu);// 插入
                menuIdsCopy.add(menu.getPid());// 将这个父级id添加到数组里面
            }
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }

    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {

        return roleMenuMapper.selectByRoleId(roleId);
    }


}
